/**
 * @description 角色用户中间表控制器
 * @author 韩
 */

const dayjs = require("dayjs")
const userForRoleCollection = require("../../../model/role&user-model")
const { getFilter } = require("../../../utils/setFilter")

// 添加用户和角色的关联
const saveDocument = async ({

    roleId,
    roleName,
    userName,
    userId,
    user_id,
}) => {
    try {
        const params = {

            createDate: dayjs(),
            roleId,
            roleName,
            userName,
            userId,
            user_id
        }
        let saveResult = null;
        const res = await userForRoleCollection.findOne({ userId: userId, user_id: user_id });
        // console.log("当前有没有这个人在里面？", res);
        if (res == null) {
            // 给这个用户分配一个角色
            saveResult = await userForRoleCollection.create({
                ...params
            })
        } else {
            // 更新修改用户归属的角色
            console.log("有这个记录了，要更新", userId);
            saveResult = await userForRoleCollection.findOneAndUpdate({ user_id: user_id }, {
                $set: {
                    ...params
                }
            }, { new: true })
        }
        if (saveResult) {
            const {
                _id,
                roleId,
                roleName,
                userName,
                userId,
                user_id
            } = saveResult

            return {
                status: "0000",
                message: "成功",
                data: {
                    _id,
                    roleId,
                    roleName,
                    userName,
                    userId,
                    user_id
                }
            }
        }
        return {
            status: "2000",
            message: "失败",
        }
    } catch (error) {
        console.log("控制出错", error);
    }



}





// 查询用户和角色的关联关系
const queryDocumentList = async ({ roleId = null, roleName = null, userName = null, userId = null }) => {
    let filter = {
        roleName: roleName && { $regex: eval("/" + roleName + "/i") },//商品名模糊查询
        userName: userName && { $regex: eval("/" + userName + "/i") },//商品名模糊查询
        roleId: roleId && { $regex: eval("/" + roleId + "/g") },
        userId: userId && { $regex: eval("/" + userId + "/g") },
    }
    filter = getFilter(filter)
    const list = await userForRoleCollection.find(filter).sort({ order: 1 })
    return list;
}


// 根据id查详情
const getDocumentDetail = async ({ userId, roleId }) => {
    try {
        const res = await userForRoleCollection.findOne({
            userId
        })
        if (res) {
            const { userId, roleId, roleName, userName, } = res;
            console.log("查找结果：\n", userId, roleId, roleName, userName,)
            return {
                userId, roleId, roleName, userName,
            }
        } else {
            return {

            }
        }
    } catch (error) {
        return {}
    }
}

// 删除用户和角色的关联
const deleteDocuments = async ({ roleIds, user_id }) => {
    console.log('调用了 删除关联表');
    let params = {
        roleId: roleIds && { $in: roleIds },
        user_id: user_id && { $in: user_id }
    }
    params = getFilter(params)
    console.log("最终删除角色关联的表的参数：\n", params)
    const deleteResult = await userForRoleCollection.deleteMany(
        // {
        //     roleId: { $in: roleIds }
        // }
        params
    );

    if (deleteResult.deletedCount) {
        return {
            status: '0000',
            message: `删除了${deleteResult.deletedCount}条数据`
        }
    } else {
        return {
            status: '0010',
            message: `删除失败`
        }
    }

}
module.exports = {
    saveDocument, queryDocumentList, deleteDocuments,
    getDocumentDetail
}